package com.cyzy.homework.controller;

import com.cyzy.homework.common.Result;
import com.cyzy.homework.dto.HomeworkFileDTO;
import com.cyzy.homework.service.FileService;
import com.cyzy.homework.service.HomeworkSubmitService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 老师端作业管理控制器
 */
@RestController
@RequestMapping("/api/teacher/homework")
@CrossOrigin(origins = "*")
public class TeacherHomeworkController {
    
    @Autowired
    private HomeworkSubmitService homeworkSubmitService;
    
    @Autowired
    private FileService fileService;
    
    /**
     * 获取指定作业的所有提交记录（老师端查看）
     */
    @GetMapping("/{homeworkId}/submissions")
    public Result<String> getHomeworkSubmissions(@PathVariable Long homeworkId) {
        try {
            // 这里需要调用服务获取所有提交记录
            // 暂时返回成功响应，实际实现需要根据具体的服务方法
            return Result.success("获取作业提交记录成功", "功能开发中");
        } catch (Exception e) {
            return Result.error("获取作业提交记录失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取学生提交的作业文件列表
     */
    @GetMapping("/submission/{submitId}/files")
    public Result<List<HomeworkFileDTO>> getSubmissionFiles(@PathVariable Long submitId) {
        try {
            List<HomeworkFileDTO> files = fileService.getFilesBySubmitId(submitId);
            
            // 为每个文件添加下载链接
            for (HomeworkFileDTO file : files) {
                try {
                    String downloadUrl = fileService.getFileDownloadUrl(file.getId());
                    file.setDownloadUrl(downloadUrl);
                } catch (Exception e) {
                    // 如果获取下载链接失败，使用默认API路径
                    file.setDownloadUrl("/api/files/download/" + file.getId());
                }
            }
            
            return Result.success("获取提交文件列表成功", files);
        } catch (Exception e) {
            return Result.error("获取提交文件列表失败: " + e.getMessage());
        }
    }
    
    /**
     * 直接下载学生提交的文件
     */
    @GetMapping("/file/{fileId}/download")
    public Result<Map<String, Object>> downloadSubmissionFile(@PathVariable Long fileId) {
        try {
            // 获取文件信息
            HomeworkFileDTO fileInfo = fileService.getFileById(fileId);
            
            // 获取MinIO预签名下载链接
            String downloadUrl = fileService.getFileDownloadUrl(fileId);
            
            Map<String, Object> result = Map.of(
                "fileName", fileInfo.getOriginalName(),
                "fileSize", fileInfo.getFileSizeFormatted(),
                "downloadUrl", downloadUrl
            );
            
            return Result.success("获取下载链接成功", result);
        } catch (Exception e) {
            return Result.error("获取文件下载链接失败: " + e.getMessage());
        }
    }
    
    /**
     * 批量下载作业文件
     */
    @PostMapping("/files/batch-download")
    public Result<List<Map<String, Object>>> batchDownloadFiles(@RequestBody Map<String, Object> request) {
        try {
            @SuppressWarnings("unchecked")
            List<Long> fileIds = (List<Long>) request.get("fileIds");
            
            if (fileIds == null || fileIds.isEmpty()) {
                return Result.error("文件ID列表不能为空");
            }
            
            List<Map<String, Object>> downloadInfo = new ArrayList<>();
            
            for (Long fileId : fileIds) {
                try {
                    HomeworkFileDTO fileInfo = fileService.getFileById(fileId);
                    String downloadUrl = fileService.getFileDownloadUrl(fileId);
                    
                    downloadInfo.add(Map.of(
                        "fileId", fileId,
                        "fileName", fileInfo.getOriginalName(),
                        "fileSize", fileInfo.getFileSizeFormatted(),
                        "downloadUrl", downloadUrl
                    ));
                } catch (Exception e) {
                    // 跳过失败的文件，继续处理其他文件
                    System.err.println("获取文件 " + fileId + " 下载链接失败: " + e.getMessage());
                }
            }
            
            return Result.success("获取批量下载链接成功", downloadInfo);
        } catch (Exception e) {
            return Result.error("批量下载失败: " + e.getMessage());
        }
    }
}
